package com.timebank.score.service.impl;

import com.timebank.common.core.exception.ServiceException;
import com.timebank.common.core.web.pojo.AjaxResult;
import com.timebank.common.security.utils.SecurityUtils;
import com.timebank.score.mapper.PrizeMapper;
import com.timebank.score.pojo.entity.Prize;
import com.timebank.score.service.PrizeService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 奖品 实现类
 * @author shiliuyinzhen
 */
@Service
public class PrizeServiceImpl implements PrizeService {

    @Resource
    private PrizeMapper prizeMapper;

    /**
     * 获取奖品列表
     *
     * @return
     */
    @Override
    public List<Prize> getPrizeList() {
        return prizeMapper.getPrizeList();
    }

    /**
     * 新增奖品
     * @param prize
     * @return
     */
    @Override
    public AjaxResult addPrize(Prize prize) {
        //检查奖品是否已经存在
        checkPrizeExist(prize);
        prize.setStock(prize.getTotal());
        prize.setCreateBy(SecurityUtils.getUsername());
        prize.setCreateTime(LocalDateTime.now());
        prize.setRemark("新增奖品");
        return prizeMapper.addPrize(prize) > 0 ?
                AjaxResult.success("新增奖品成功") : AjaxResult.error("新增奖品失败");
    }

    /**
     * 批量删除奖品
     * @param prizeIds
     * @return
     */
    @Override
    public AjaxResult batchDeletePrize(Long[] prizeIds) {
        return prizeMapper.batchDeletePrize(prizeIds) > 0 ?
                AjaxResult.success("删除奖品成功") : AjaxResult.error("删除奖品失败");
    }

    /**
     * 修改奖品信息
     * @param prize
     * @return
     */
    @Override
    public AjaxResult updatePrize(Prize prize) {
        //检查奖品是否已经存在
        checkPrizeExist(prize);
        prize.setUpdateBy(SecurityUtils.getUsername());
        prize.setUpdateTime(LocalDateTime.now());
        prize.setRemark("修改奖品信息");
        return prizeMapper.updatePrize(prize) > 0 ?
                AjaxResult.success("修改奖品成功") : AjaxResult.error("修改奖品失败");
    }

    /**
     * 检查奖品是否已经存在
     * @param prize
     */
    public void checkPrizeExist(Prize prize){
       Prize prize1 = new Prize();
       prize1.setName(prize.getName());
       Prize prize2 = prizeMapper.getPrize(prize1);
       if (prize2 != null){
           //如果新增奖品即没有id，或者存在名字相同且和修改的id不同
           if (prize.getId() == null
                || !prize.getId().equals(prize2.getId())){
               throw new ServiceException(prize.getName() + " 已经存在");
           }
       }
    }

    /**
     * 查询奖品信息
     * @param prize
     * @return
     */
    @Override
    public Prize getPrize(Prize prize) {
        return prizeMapper.getPrize(prize);
    }
}
